﻿using ABCNet.Authorization.Users;
using ABCNet.Orders.Dto;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;

namespace ABCNet.Orders
{
    /// <summary>
    /// 订单信息
    /// </summary>
    public class OrderAppService : ABCNetAppServiceBase
    {

        private readonly IRepository<Order> _repository;
        private readonly IRepository<User, long> _userRepository;

        public OrderAppService(IRepository<Order> repository,
            IRepository<User, long> userRepository)
        {
            _repository = repository;
            _userRepository = userRepository;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<OrderDto>> GetOrderPageList(OrderQueryInput input)
        {
            var query = from order in _repository.GetAll()
                            .WhereIf(AbpSession.AccountType == AccountTypes.会员账户, x => x.UserId == AbpSession.UserId)
                            .WhereIf(input.OrderState != null && input.OrderState.HasValue, x => x.OrderState == input.OrderState.Value)
                            .WhereIf(input.StartDate != null && input.StartDate.HasValue, x => x.CreationTime >= input.StartDate.Value.Date)
                            .WhereIf(input.EndDate != null && input.EndDate.HasValue, x => x.CreationTime < input.EndDate.Value.Date.AddDays(1))
                        join user in _userRepository.GetAll() on order.UserId equals user.Id
                        orderby order.CreationTime descending
                        select new OrderDto()
                        {
                            Id = order.Id,
                            Consignee = order.Consignee,
                            ConsigneeAddress = order.ConsigneeAddress,
                            ConsigneeTel = order.ConsigneeTel,
                            ExpressCompanyName = order.ExpressCompanyName,
                            ExpressNumber = order.ExpressNumber,
                            OrderState = order.OrderState,
                            UserId = order.UserId,
                            CreationTime = order.CreationTime,
                            CreatorUserId = order.CreatorUserId,
                            ExpressDeliveryTime = order.ExpressDeliveryTime,
                            CompletedTime = order.CompletedTime,
                            UserName = user.UserName,
                            Name = user.Name
                        };

            //总行数
            var totalCount = await query.CountAsync();

            int startIndex = (input.StartPage - 1) * input.PageCount;
            query = query.Skip(startIndex).Take(input.PageCount);
            //获取对象
            var rlst = await query.ToListAsync();

            //组装分页返回对象
            var PagedResult = new PagedResultDto<OrderDto>(totalCount, rlst);
            return PagedResult;
        }
        
        /// <summary>
        /// 发货信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public void Delivery(OrderDeliveryInput input)
        {
            if (AbpSession.AccountType != AccountTypes.后台账户)
                throw new UserFriendlyException("只有管理员才能填写发货信息！");
            var order = _repository.Get(input.Id);
            if(order.OrderState == OrderStates.未发货)
            {
                order.OrderState = OrderStates.已发货;
                order.ExpressDeliveryTime = Abp.Timing.Clock.Now;
                order.ExpressCompanyName = input.ExpressCompanyName;
                order.ExpressNumber = input.ExpressNumber;
                _repository.Update(order);
            }
        }

        /// <summary>
        /// 完成订单（用户已收货）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public void Complete(EntityDto input)
        {
            //if (AbpSession.AccountType != AccountTypes.后台账户)
            //    throw new UserFriendlyException("只有管理员才能审核！");
            var order = _repository.Get(input.Id);
            if (order.OrderState == OrderStates.已发货)
            {
                order.OrderState = OrderStates.已收货;
                order.CompletedTime = Abp.Timing.Clock.Now;
                _repository.Update(order);
            }
        }
    }
}
